package org.ncibi.cytoscape.metscape.task;

import java.io.File;

import org.ncibi.cytoscape.metscape.data.GeneData;

import cytoscape.Cytoscape;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;

public class ImportGeneFileTask implements Task {

	private TaskMonitor taskMonitor;
	private boolean interrupted = false;
	private File geneFile;
	private GeneData geneData;

	public static GeneData importFrom(File geneFile) {
		ImportGeneFileTask task = new ImportGeneFileTask(geneFile);
		return configureAndRunTask(task);
	}

	private ImportGeneFileTask(File geneFile) {
		this.geneFile = geneFile;
	}

	private static GeneData configureAndRunTask(ImportGeneFileTask task) {
		// Configure JTask Dialog Pop-Up Box
		JTaskConfig jTaskConfig = new JTaskConfig();
		jTaskConfig.setOwner(Cytoscape.getDesktop());
		jTaskConfig.displayCancelButton(true);
		jTaskConfig.displayStatus(true);

		// Execute Task in New Thread; pops open JTask Dialog Box.
		if(TaskManager.executeTask(task, jTaskConfig)) {
			return task.geneData;
		}
		else return null;
	}

	public void setTaskMonitor(TaskMonitor monitor)
			throws IllegalThreadStateException {
		taskMonitor = monitor;
	}

	public void halt() {
		interrupted = true;
	}

	public String getTitle() {
		return "Import Gene File";
	}

	public void run() {
		try {
			interrupted = false;
			taskMonitor.setPercentCompleted(-1);
			taskMonitor.setStatus("Initializing...");

			if (geneFile != null) {
				taskMonitor.setStatus("Importing gene file...");
				geneData = GeneData.parse(geneFile);
				if (geneData == null
						|| geneData.idSet().isEmpty()
						|| interrupted)
					throw new Exception("Importing gene file failed. Either the file could not be read, or it may not be in the correct format.");
			}

			taskMonitor.setStatus("Complete");
			taskMonitor.setPercentCompleted(100);
		}

		catch (Throwable t) {
			if (!interrupted)
				taskMonitor.setException(t,
						"An error occurred while loading data for the MetScape session: "
								+ t.getLocalizedMessage());
		}
	}
}
